import styles from "./index.module.less"
import { make } from "../../utils/dom"

class PaperTool {
	static get isInline() {
		return true
	}

	get toolboxIcon() {
		return `<svg xmlns="http://www.w3.org/2000/svg" width="1em" height="1em" viewBox="0 0 24 24"><path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2zm4 2h6m-6 4h6m-6 4h4"/></svg>`
	}

	static get sanitize() {
		return {
			p: true,
		}
	}

	static get shortcut() {
		return "CTRL+P"
	}

	static get title() {
		return "批注"
	}

	clear() {
		this.hideActions()
	}

	get state() {
		return this._state
	}

	set state(state) {
		this._state = state

		this.button.classList.toggle(this.api.styles.inlineToolButtonActive, state)
	}

	constructor({ api }) {
		this.api = api
		this.button = null
		this._state = false

		this.tag = "P"
		this.class = styles["cdx-paper"]
		this.popClass = styles["pop"]
	}

	render() {
		this.button = make("button", styles["paper"], { type: "button" })
		this.button.innerHTML = this.toolboxIcon
		this.button.classList.add(this.api.styles.inlineToolButton)

		return this.button
	}

	// 应用插件时执行此方法
	surround(range) {
		if (this.state) {
			this.unwrap(range)
			return
		}

		this.wrap(range)
	}

	wrap(range) {
		const selectedText = range.extractContents()
		const mark = make(this.tag, this.class)

		mark.appendChild(selectedText)
		range.insertNode(mark)

		this.api.selection.expandToTag(mark)
	}

	unwrap(range) {
		const mark = this.api.selection.findParentTag(this.tag)
		const text = range.extractContents()

		mark.remove()

		range.insertNode(text)
	}

	// 选中内容时执行此方法
	checkState(selection) {
		const mark = this.api.selection.findParentTag(this.tag, this.class)
		this.state = !!mark

		if (this.state) {
			this.showActions(mark)
		} else {
			this.hideActions()
		}
	}

	renderActions() {
		this.paperEl = make("span", styles["paperEl"])
		this.textarea = make("textarea", styles["textarea"], { row: 3 })
		this.saveBtn = make("span", styles["btn"], { innerHTML: "保存" })
		this.paperEl.append(this.textarea, this.saveBtn)

		return this.paperEl
	}

	showActions(mark) {
		this.paperEl.style.display = "inline-block"
		const pop = mark.querySelector(`.${this.popClass}`)
		if (pop) {
			this.textarea.value = pop.innerHTML
		}
		this.saveBtn.onclick = () => {
			const value = this.textarea.value
			const pop = make("span", this.popClass, { innerHTML: value })
			mark.append(pop)
			this.hideActions()
		}
	}

	hideActions() {
		this.textarea.onchange = null
		this.saveBtn.onclick = null
		this.paperEl.style.display = "none"
	}
}
export default PaperTool

